#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <cassert>
#include <sys/wait.h>
using namespace std;


void PrintSig(sigset_t &pending)
{
    cout<<"Pending bitmap:"<<endl;
    for(int i=31;i>0;i--)//i为比特位，也是信号编号
    {
        if(sigismember(&pending,i))
        {
            cout<<"1";
        }
        else
        {
            cout<<"0";
        }
    }
    cout<<endl;
}
void handler(int sig)
{
    sigset_t pending;
    sigemptyset(&pending);
    int n = sigpending(&pending);//正在处理2号信号
    assert(n==0);
    cout<<"递达中..."<<endl;
    PrintSig(pending);
    cout<<sig<<"号信号被递达处理"<<endl;

}

int main()
{
    //对2号信号进行自定义捕捉
    signal(2,handler);
    sigset_t block,o_block;
    //屏蔽2号信号
    sigemptyset(&block);
    sigemptyset(&o_block);
    sigaddset(&block,2);
    //进入内核
    int n = sigprocmask(SIG_SETMASK,&block,&o_block);
    assert(n==0);
    cout<<"block 2 signal success"<<"pid:"<<getpid()<<endl;
    int cnt = 0;
    while(1)
    {
        sigset_t pending;
        sigemptyset(&pending);
        n = sigpending(&pending);
        assert(n == 0);
        //打印pending位图中收到的信号
        PrintSig(pending);
        cnt++;
        //解除对2号信号的屏蔽
        if(cnt==10)
        {
            n = sigprocmask(SIG_UNBLOCK,&block,&o_block);
            assert(n==0);
        }
        sleep(1);
    }

    return 0;
}